package com.shuziren.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.shuziren.entity.SysMenu;
import com.shuziren.entity.vo.MenuVO;
import com.shuziren.mapper.SysMenuMapper;
import com.shuziren.service.ISysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author CX330
 * @since 2025-05-04
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    @Override
    public List<MenuVO> getMenuTree() {
        // 获取所有菜单
        List<SysMenu> allMenus = this.list();

        // 转换为VO对象
        List<MenuVO> menuVOs = allMenus.stream()
                .map(menu -> {
                    MenuVO vo = new MenuVO();
                    BeanUtils.copyProperties(menu, vo);
                    return vo;
                })
                .collect(Collectors.toList());

        // 按父ID分组
        Map<Long, List<MenuVO>> parentMap = menuVOs.stream()
                .collect(Collectors.groupingBy(MenuVO::getParentId));

        // 获取顶级菜单
        List<MenuVO> rootMenus = parentMap.getOrDefault(0L, new ArrayList<>());

        // 递归构建树形结构
        rootMenus.forEach(menu -> buildTree(menu, parentMap));

        return rootMenus;
    }

    private void buildTree(MenuVO menu, Map<Long, List<MenuVO>> parentMap) {
        List<MenuVO> children = parentMap.get(menu.getId());
        if (children != null) {
            menu.setChildren(children);
            children.forEach(child -> buildTree(child, parentMap));
        }
    }
}
